package com.tencent.wxcloudrun.frontcontroller;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.dto.UserDetail;
import com.tencent.wxcloudrun.dto.UserLevel;
import com.tencent.wxcloudrun.dto.BaseUserDetail;

import com.tencent.wxcloudrun.dto.*;
import com.tencent.wxcloudrun.mapper.UsersMapper;
import com.tencent.wxcloudrun.model.SmsCodeResponse;
import com.tencent.wxcloudrun.uitls.SmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.tencent.wxcloudrun.uitls.JwtTokenUtils.createToken;
import static com.tencent.wxcloudrun.uitls.JwtTokenUtils.createTokenBymobile;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/3/2 23:16
 * @description: TODO
 */
@RestController
@Api(tags = "用户模块")
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    UsersMapper usersMapper;
    @Resource
    private  RedisTemplate<String, String> redisTemplate;

    /**
     * @return
     */
    @Operation(summary = "微信小程序登陆免code")
    @PostMapping(value = "/wxcloud/login")
   public WeixinloginResponse login(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        WeixinloginResponse response = new WeixinloginResponse();
        Users users = usersMapper.selectByOpenid(openid);
        if (users == null){
            Users users1 = new Users();
            users1.setOpenid(openid);
            usersMapper.insert(users1);
            Integer id = users1.getId();
            response.setCode(200);
            response.setMsg("ok");
            WexinLoginResult wexinLoginResult = new WexinLoginResult();
            wexinLoginResult.setUid(String.valueOf(id));
            wexinLoginResult.setOpenid(openid);
            response.setData(wexinLoginResult);
        }else {
            response.setCode(200);
            response.setMsg("ok");
            WexinLoginResult wexinLoginResult = new WexinLoginResult();
            wexinLoginResult.setUid(String.valueOf(users.getId()));
            wexinLoginResult.setOpenid(openid);
            response.setData(wexinLoginResult);
        }

        return response;
    }

    @Operation(summary = "微信小程序支付免code")
    @PostMapping(value = "/wxcloud/pay")
    public ResponseBase wxpay(HttpServletRequest request, @RequestBody WxpayRequest wxpayRequest) {
        ResponseBase responseBase = new ResponseBase();
        return responseBase;
    }

    @Operation(summary = "微信小程序获取用户信息免code")
    @PostMapping(value = "/wxcloud/userDetail")
    public UserDetailResponse userDetail(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        Users users = usersMapper.selectByOpenid(openid);
        BaseUserDetail baseUserDetail = new BaseUserDetail();
        baseUserDetail.setId(users.getId().toString());
        baseUserDetail.setNick(users.getNick());
        baseUserDetail.setAvatarUrl(users.getAvatarurl());
        baseUserDetail.setMobile(users.getPhone());
        UserLevel userLevel = new UserLevel();
        userLevel.setName(users.getUserlevelname());
        userLevel.setRebate(users.getRebate());
        userLevel.setUpgradeAmount(users.getUpgradeamount());
        UserDetail userDetail = new UserDetail();
        userDetail.setBase(baseUserDetail);
        userDetail.setUserLevel(userLevel);
        UserDetailResponse userDetailResponse = new UserDetailResponse();
        userDetailResponse.setData(userDetail);
        userDetailResponse.setCode(0);
        userDetailResponse.setMsg("ok");
        return userDetailResponse;
    }


    /**
     * 评价接口
     */

    @Operation(summary = "微信小程序评价接口免code")
    @PostMapping(value = "/wxcloud/orderReputation")
    public ResponseBase orderReputation(HttpServletRequest request, @RequestBody OrderReputationResquest json) {


        return null;
    }



    /**
     * 查看用户资产
     */
    @Operation(summary = "微信小程序查看用户资产免code")
    @PostMapping(value = "/wxcloud/userAmount")
    public  UserAmountResponse userAmount(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        Users users = usersMapper.selectByOpenid(openid);
        UserAmountResponse userAmountResponse = new UserAmountResponse();
        UserAmount userAmount = new UserAmount();
        userAmount.setBalance(users.getBalance());
        userAmount.setScore(users.getScore());
        userAmountResponse.setCode(0);
        userAmountResponse.setMsg("ok");
        userAmountResponse.setData(userAmount);
        return userAmountResponse;
    }



    /**
     * 修改用户昵称
     */
    @Operation(summary = "微信小程序修改用户昵称免code")
    @PostMapping(value = "/wxcloud/modifyUserInfo")
    public ModifyUserInfoResponse modifyUserInfo(HttpServletRequest request, @RequestBody ModifyUserInfo json) {
        String openid = request.getHeader("X-WX-OPENID");
        String nick = json.getNick();
        String avatarUrl = json.getAvatarUrl();
        if (nick != null && avatarUrl == null){
            ModifyUserInfoResponse modifyUserInfoResponse = new ModifyUserInfoResponse();
            int i = usersMapper.updateNickByOpenid(openid, nick);
            if (i>0){
                Users users = usersMapper.selectByOpenid(openid);
                ModifyUserInfo modifyUserInfo = new ModifyUserInfo();
                modifyUserInfo.setNick(users.getNick());
                modifyUserInfo.setAvatarUrl(users.getAvatarurl());
                modifyUserInfoResponse.setData(modifyUserInfo);
                modifyUserInfoResponse.setCode(0);
                modifyUserInfoResponse.setMsg("ok");
                return modifyUserInfoResponse;
            }else {
                modifyUserInfoResponse.setCode(1);
                modifyUserInfoResponse.setMsg("修改失败");
                return modifyUserInfoResponse;
            }
        }else {
            ModifyUserInfoResponse modifyUserInfoResponse = new ModifyUserInfoResponse();
            int i = usersMapper.updateavAtarUrlByOpenid(openid, avatarUrl);
            if (i > 0) {
                Users users = usersMapper.selectByOpenid(openid);
                ModifyUserInfo modifyUserInfo = new ModifyUserInfo();
                modifyUserInfo.setNick(users.getNick());
                modifyUserInfo.setAvatarUrl(users.getAvatarurl());
                modifyUserInfoResponse.setData(modifyUserInfo);
                modifyUserInfoResponse.setCode(0);
                modifyUserInfoResponse.setMsg("ok");
                return modifyUserInfoResponse;
            } else {
                modifyUserInfoResponse.setCode(1);
                modifyUserInfoResponse.setMsg("修改失败");
                return modifyUserInfoResponse;
            }

        }

    }



    @Operation(summary = "绑定手机号免code")
    @PostMapping("/wxcloud/bindMobileWxapp")
    public BindMobile bindMobileWxapp(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        BindMobile bindMobile = new BindMobile();
        bindMobile.setCode(200);
        bindMobile.setData("17778479306");
        bindMobile.setMsg("ok");
        return bindMobile;
    }


    /**
     * 无限生成小程序码
     */
    @Operation(summary = "无限生成小程序码")
    @PostMapping("/wxcloud/wxaQrcode")
    public WxaQrcodeResponse wxaQrcode(HttpServletRequest request,@RequestBody WxaQrcodeRequest json){
        return null;
    }




    /**
     * 扫码token
     */
    @Operation(summary = "扫码token")
    @PostMapping("/wxcloud/cyTableToken")
    public JSONObject cyTableToken(HttpServletRequest request, @RequestBody JSONObject json){
        String openid = request.getHeader("X-WX-OPENID");
        Integer uid = usersMapper.selectByOpenid(openid).getId();
        String tableId = json.getString("tableId");
        String key = json.getString("key");
        String token = createToken(openid, tableId, key, true);
        JSONObject data = new JSONObject();
        data.put("token", token);
        data.put("uid", uid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", data);
        jsonObject.put("msg", "ok");
        return jsonObject;
    }

    /**
     * 短信验证获取发送
     * @param request
     * @param json
     * @return
     */
    @Operation(summary = "短信验证获取发送")
    @PostMapping("/wxcloud/smsCode")
    public JSONObject smsCode(HttpServletRequest request, @RequestBody JSONObject json){
        String openid = request.getHeader("X-WX-OPENID");
        String mobile = json.getString("mobile");
        String smsCode = createSmsCode();
        saveSmsCode(mobile, smsCode);
        boolean b = SmsUtil.sendSms(mobile, smsCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", b);
        return jsonObject;
    }


    /**
     * 生成6位随机数
     * @return
     */
    public static String createSmsCode() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }


    /**
     * 临时保存code 用于验证
     * @param mobile
     * @param smsCode
     */
    private  void saveSmsCode(String mobile, String smsCode) {
        redisTemplate.opsForValue().set(mobile, smsCode, 300, TimeUnit.SECONDS);
        log.info("手机号：{}，验证码：{}", mobile, smsCode);
    }


    /**
     * 手机验证码登陆
     * @param request
     * @param json
     * @return
     */
    @Operation(summary = "手机验证码登陆")
    @PostMapping("/wxcloud/loginByMobile")
    public JSONObject loginByMobile(HttpServletRequest request, @RequestBody JSONObject json){
        String mobile = json.getString("mobile");
        String code = json.getString("code");
        String smsCode = (String) redisTemplate.opsForValue().get(mobile);
        if (smsCode == null) {
            throw new RuntimeException("验证码已过期");
        }
        if (!smsCode.equals(code)) {
            throw new RuntimeException("验证码不正确");
        }
        Users users = usersMapper.selectByMobile(mobile);
        if (users == null) {
            users = new Users();
            users.setMobile(mobile);
            users.setAddtime(String.valueOf(LocalDateTime.now()));
            usersMapper.insert(users);
        }
        log.info("用户：{}，登陆成功", mobile);
        String token = createTokenBymobile(mobile, true);
        log.info("用户：{}，token：{}", mobile, token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "ok");
        jsonObject.put("data", token);
        return jsonObject;
    }













}


